/**
 * Created by wangshuyi on 1/20/2017, 9:18:54 AM.
 */

'use strict';

const extend = require('extend');

const express = require('express');
const router = express.Router();

const logger = require('log4js').getLogger("sys");

const resUtil = require("../../module/util/resUtil");
const reqUtil = require("../../module/util/reqUtil");
const tool = require("../../module/util/tool");

const BookcaseService = require('../../service/article/BookcaseService');
const ArticleService = require('../../service/article/ArticleService');
const FileService = require("../../service/system/tool/FileService");
const config = require("../../config/config");

router.get('/articleView/:articleCode', function (req, res, next) {
    let articleCode = req.params.articleCode;
    ArticleService.findOne(config.dbUser.admin, {code: articleCode}, 'bookcase').then(article => {
        res.render('article/articleView', extend({}, {body: article || {}}));
    });
});

router.get('/catalog', function (req, res, next) {
    let bookId = req.query.bookcase;
    BookcaseService.find(config.dbUser.admin, {parent: bookId}, "icon parent", {sort: 1})
        .then(
            data => res.render('article/template/catalog', {data: data}),
            err => res.render('article/template/errorPage')
        )
});

router.get('/searchCatalog', function (req, res, next) {
    let bookcase = req.query.bookcase;
    BookcaseService.find(config.dbUser.admin, {parent: bookcase}, "icon parent", {sort: 1})
        .then(
            data => res.render('article/template/searchCatalog', {id: bookcase, data: data}),
            err => res.render('article/template/errorPage')
        )
});

router.get('/bannerPage', function (req, res, next) {
    let bcId = req.query.bookcase,
        list,
        resList=[];
    BookcaseService.findById(config.dbUser.admin, {_id: bcId}).then(bookcase => {
        if(!bookcase){
            res.render('article/template/errorPage');
        }
        if (bookcase.bannerImgs) {
            let ids = bookcase.bannerImgs;
            let arr = ids.split(',');
            let count = 0;
            let result = [];
            for (let i = 0; i < arr.length; i++) {
                FileService.find(config.dbUser.admin, {_id:arr[i]}).then(function (data) {
                    count++;
                    list = data;
                    result.push(data);
                    if(count===arr.length){
                        ArticleService.find(config.dbUser.admin, {bookcase:bcId},'img bookcase',{sort:1}).then(function (data) {
                            res.render('article/template/bannerPage', {bannerList: result, articleList:tool.filterByDate(data)})
                        },function (err) {
                            res.render('article/template/errorPage')
                        })
                    }
                })
            }
        } else {
            ArticleService.find(config.dbUser.admin, {bookcase: bcId}, 'img bookcase', {sort: 1}).then(function (data) {
                list = data;
                res.render('article/template/noBannerPage', {articleList: list})
            }, function (error) {
                res.render('article/template/errorPage')
            })
        }
    },err=>{
        res.render('article/template/errorPage')
    });
});
// router.get('/tabPage', function (req, res, next) {
//     let bcId = req.query.bookcase, list;
//     ArticleService.find(config.dbUser.admin, {bookcase: bcId}, 'img bookcase', {sort: 1}).then(function (data) {
//         let pastArr = [];
//         let nowArr = [];
//         list = data;
//         for (let i = 0; i < list.length; i++) {
//             if (list[i].disActiveTime < new Date()) {
//                 pastArr.push(list[i])
//             } else {
//                 nowArr.push(list[i])
//             }
//         }
//         res.render('article/template/tabPage', {id:bcId,nowArr: nowArr, pastArr: pastArr})
//     }, function (error) {
//         res.render('article/template/errorPage')
//     })
// });

router.get('/tabPage', function (req, res, next) {
    let bcId = req.query.bookcase, list;
    ArticleService.find({}, {bookcase: bcId}, 'img bookcase', {sort: 1}).then(function (data) {
        let pastArr = [];
        let nowArr = [];
        list = data;
        for (let i = 0; i < list.length; i++) {
            if (list[i].disActiveTime < new Date()) {
                if(pastArr.length<20){//控制几条
                    pastArr.push(list[i])
                }
            } else {
                nowArr.push(list[i])
            }
        }
        res.render('article/template/tabPage', {id:bcId,nowArr: nowArr, pastArr: pastArr})
    }, function (error) {
        res.render('article/template/errorPage')
    })
});

router.get('/tabPastForPage', function (req, res, next) {
    let bcId = req.query.bookcase, list,
        pageSize=req.query.pageSize,
        pageNumber=req.query.pageNumber,
        condition={},
        now=new Date();
    condition.bookcase = bcId;
    condition.disActiveTime={"$lte" : now};
    ArticleService
        .findForPage(config.dbUser.admin, pageSize,pageNumber,condition, 'img bookcase', {sort: 1}).then(function (data) {
        res.send(resUtil.success({data:data}))
    }, function (error) {
        res.render('article/template/errorPage')
    })
});

router.get('/noBannerPage', function (req, res, next) {
    let bcId = req.query.bookcase, list;
    ArticleService.find(config.dbUser.admin, {bookcase: bcId}, 'img bookcase', {sort: 1}).then(function (data) {
        list = data;
        res.render('article/template/noBannerPage', {articleList: tool.filterByDate(list)})
    }, function (error) {
        res.render('article/template/errorPage')
    })
});

router.get('/searchList', function (req, res, next) {
    let bcId = req.query.bookcase, list;
    ArticleService.find(config.dbUser.admin, {bookcase: bcId}, 'img bookcase', {sort: 1})
        .then(function (data) {
            list = data;
            res.render('article/template/searchList', {id: bcId, articleList: tool.filterByDate(list)})
        }, function (error) {
            res.render('article/template/errorPage')
        })
});

router.get('/team', function (req, res, next) {
    let bcId = req.query.bookcase, list;
    ArticleService.find(config.dbUser.admin, {bookcase: bcId}, 'img bookcase', {sort: 1}).then(function (data) {
        list = data;
        res.render('article/template/team', {articleList: tool.filterByDate(list)})
    }, function (error) {
        res.render('article/template/errorPage')
    })
});

router.get('/togglePage', function (req, res, next) {
    let bcId = req.query.bookcase, list;
    ArticleService.find(config.dbUser.admin, {bookcase: bcId}, 'img bookcase', {sort: 1}).then(function (data) {
        list = data;
        res.render('article/template/togglePage', {articleList: tool.filterByDate(list)})
    }, function (error) {
        res.render('article/template/errorPage')
    })
});

router.get('/noPicCatalogPage', function (req, res, next) {
    let bcId = req.query.bookcase;
    BookcaseService.find(config.dbUser.admin, {parent: bcId}, "icon parent", {sort: 1})
        .then(
            data => res.render('article/template/noPicCatalogPage', {data: data}),
            err =>  res.render('article/template/errorPage')
        )
});

router.get('/noPicPage', function (req, res, next) {
    let bcId = req.query.bookcase, list;
    ArticleService.find(config.dbUser.admin, {bookcase: bcId}, 'img bookcase', {sort: 1}).then(function (data) {
        list = data;
        res.render('article/template/noPicPage', {data: tool.filterByDate(list)})
    }, function (error) {
        res.render('article/template/errorPage')
    })
});

router.get('/search', function (req, res, next) {
    let bcId = req.query.bookcase, list,
        condition = {},
        str = req.query.con;
    /*    if (str) {
     condition = {
     bookcase: bcId,
     "$or": [{name: {"$regex": str}}, {summary: {"$regex": str}}]
     };
     } else {
     condition = {
     bookcase: bcId
     }
     }*/
    if (str) {
        condition = {
            "$or": [{name: {"$regex": str}}, {summary: {"$regex": str}}]
        };
    }
    ArticleService.find({}, condition, 'img parent bookcase', {sort: 1}).then(function (data) {
        list = data;
        res.render('article/template/searchList', {id: bcId, articleList: tool.filterByDate(list)})
    }, function (error) {
        res.render('article/template/errorPage')
    })
});

router.get('/searchAll', function (req, res, next) {
    let bookcaseId = req.query.bookcase;
    let condition = {},searchStr = req.query.con;
    if(searchStr){
        condition = {
            "$or": [{name: {"$regex": searchStr}}, {summary: {"$regex": searchStr}}]
        };
    }
    ArticleService.find({}, condition,'img bookcase').then(articles => {
        res.render('article/template/searchList', {id:bookcaseId,articleList: tool.filterByDate(articles)})
    },err=>{
        res.render('article/template/errorPage')
    })
    /*    BookcaseService.find(config.dbUser.admin, {parent: bookcaseId}).then(bookcases => {
     let idList = [],resList=[],
     now = new Date();
     bookcases.forEach(bookcase => {
     idList.push(bookcase._id);
     });
     condition.bookcase = {$in: idList};
     ArticleService.find(config.dbUser.admin, condition,'img').then(articles => {
     res.render('article/template/searchList', {id:bookcaseId,articleList: tool.filterByDate(articles)})
     },err=>{
     res.render('article/template/errorPage')
     })
     },err=>{
     res.render('article/template/errorPage')
     });*/
});

router.get('/mixPage',function (req,res,next) {
    let bcid = req.query.bookcase;
    let mixList = [];
    ArticleService.find(config.dbUser.admin, {bookcase:bcid},'img bookcase').then(function (articles) {
        articles.forEach(function (value) {
            mixList.push(value)
        });
        BookcaseService.find(config.dbUser.admin, {parent:bcid},"icon parent").then(function (bookcases) {
            bookcases.forEach(function (value) {
                mixList.push(value);
            });
            function compare(property){
                return function(a,b){
                    let value1 = a[property];
                    let value2 = b[property];
                    return value1 - value2;
                }
            }
            mixList.sort(compare('sort'));
            res.render('article/template/mixCatalog', {id:bcid,data: mixList})
        })

    })
});


module.exports = router;
